import React, { useState } from 'react';
import { Form, message, Modal, Input, Radio, Select, ConfigProvider } from 'antd';
import request from '@/utils/request';
import styles from '@/pages/Flow/Mine/WaitApproval/ProxyModal.less';
import SimpleDataTable from '@/components/DataTable/SimpleDataTable';
// import { searchEmployee } from '@/pages/WorkFlow/components/CustomComponents/TurnoverByLeader/service';
import { debounce } from 'lodash';
import { listTemplateAndAgent, saveOrUpdate } from './service';

const { Option } = Select;

const EditableContext = React.createContext();

class EditableCell extends React.Component {
    state = {
        options: [],
        loading: false
    };

    fetchUsers = debounce(async value => {
        this.setState({
            loading: true
        });

        const response = await request(`/api/uc/approve/v1/employee/detail/info/not/quited/list?name=${value}`, {
            method: 'GET'
        });

        if (response.code === 10000) {
            this.setState({
                options: response.data,
                loading: false
            });
        }
    }, 300);

    componentWillReceiveProps(nextProps) {
        const { editing, dataIndex, record } = this.props;
        if (dataIndex === 'proxyUserCode' && nextProps.editing !== editing && nextProps.editing) {
            const { proxyEnable, proxyUserName } = record;
            this.fetchUsers(proxyEnable === 0 && proxyUserName ? proxyUserName : ''); // 如果有代理人就查下代理人，否则就查询默认前几个人！这块应该要后续产品梳理下需求
        }
    }

    handleProxyChange = (e, setFieldsValue) => {
        // const { dataIndex, record } = this.props;
        const { value } = e.target;

        if (value === 1) {
            setFieldsValue({
                proxyUserCode: '',
                proxyUserName: ''
            });
        }
    };

    handleChange = (value, setFieldsValue) => {
        const { options } = this.state;
        const find = options.find(item => item.employeeCode === value);
        if (find) {
            setFieldsValue({
                proxyUserName: find.employeeName
            });
        }
    };

    handleSearch = value => {
        this.fetchUsers(value);
    };

    getInput = (_, setFieldsValue, getFieldValue) => {
        const { options, loading } = this.state;
        const { inputType } = this.props;
        if (inputType === 'proxyEnable') {
            return (
                <Radio.Group onChange={e => this.handleProxyChange(e, setFieldsValue)}>
                    <Radio value={0}>是</Radio>
                    <Radio value={1}>否</Radio>
                </Radio.Group>
            );
        }
        if (inputType === 'proxyUserCode') {
            return (
                <Select
                    disabled={getFieldValue('proxyEnable') === 1}
                    style={{ width: 150 }}
                    showSearch
                    loading={loading}
                    defaultActiveFirstOption={false}
                    showArrow={false}
                    filterOption={false}
                    notFoundContent={null}
                    onSearch={this.handleSearch}
                    onChange={value => this.handleChange(value, setFieldsValue)}
                >
                    {options.map(option => (
                        <Option key={option.employeeCode} value={option.employeeCode}>
                            {option.employeeName}
                        </Option>
                    ))}
                </Select>
            );
        }
        return <Input />;
    };

    getRules = () => [
        {
            required: true,
            message: '请设置代理人后提交保存!'
        }
    ];

    renderCell = ({ getFieldDecorator, setFieldsValue, getFieldValue }) => {
        const { editing, dataIndex, title, inputType, record, index, children, ...restProps } = this.props;
        return (
            <td {...restProps}>
                {editing ? (
                    <Form.Item style={{ margin: 0 }}>
                        {getFieldDecorator(dataIndex, {
                            rules: getFieldValue('proxyEnable') === 0 ? this.getRules() : [],
                            initialValue:
                                // 这个赋值逻辑有问题，简单修复下！！！
                                // eslint-disable-next-line no-nested-ternary
                                dataIndex === 'proxyUserCode'
                                    ? getFieldValue('proxyEnable') === 0
                                        ? record[dataIndex]
                                        : undefined
                                    : record[dataIndex]
                        })(this.getInput(record[dataIndex], setFieldsValue, getFieldValue))}
                        {dataIndex === 'proxyUserCode' &&
                            getFieldDecorator('proxyUserName', {
                                initialValue: record?.proxyEnable === 0 ? record?.proxyUserName : '' // 这里赋值还要加个判断前面组件是否选项的逻辑！！！
                            })(<Input type="hidden" />)}
                    </Form.Item>
                ) : (
                    children
                )}
            </td>
        );
    };

    render() {
        return <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>;
    }
}

const NewProxyModal = ({ onOk, form, visible, ...rest }) => {
    const currentUser = localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')) : {};
    const [editingKey, setEditingKey] = useState('');
    const [dataSource, setDataSource] = useState([]);
    const components = {
        body: {
            cell: EditableCell
        }
    };
    // const handleSave = async row => {};

    const getData = async ({ pageSize, current }) => {
        if (visible) {
            const response = await listTemplateAndAgent({
                pageNo: current,
                pageSize,
                employeeCode: currentUser.employeeCode,
                organizationCode: currentUser.currentOrgCode
            });
            if (response.code === 10000) {
                setDataSource(response.data.rows);
                return {
                    current: response.data.pageNo,
                    pageSize: response.data.pageSize,
                    data: response.data.rows,
                    total: response.data.total
                };
            }
            message.error(response.msg);
            return {
                data: [],
                current: 1,
                pageSize: 10,
                total: 0
            };
        }
        return {
            data: [],
            current: 1,
            pageSize: 10,
            total: 0
        };
    };

    const isEditing = record => record.processKey === editingKey;

    const cancel = () => {
        setEditingKey('');
    };

    const save = (newForm, record) => {
        newForm.validateFields(async (error, row) => {
            if (error) {
                return;
            }

            const response = await saveOrUpdate({
                ...row,
                processKey: record.processKey,
                processName: record.processName,
                id: record.id
            });
            if (response.code === 10000) {
                message.success('保存成功！');
                const newData = [...dataSource];
                const index = newData.findIndex(item => record.processKey === item.processKey);
                const item = newData[index];
                newData.splice(index, 1, {
                    ...item,
                    ...row,
                    id: response.data.id
                });
                setDataSource(newData);
                setEditingKey('');
            } else {
                message.error(response.msg);
            }
        });
    };

    const edit = key => {
        setEditingKey(key);
    };
    const columns = [
        {
            title: '流程',
            dataIndex: 'processName',
            key: 'processName'
        },
        {
            title: '适用公司',
            dataIndex: 'companyName',
            key: 'companyName'
        },
        {
            title: '是否委托代理',
            dataIndex: 'proxyEnable',
            key: 'proxyEnable',
            editable: true,
            render(text) {
                return text === 0 ? '是' : '否';
            }
        },
        {
            title: '代理人',
            dataIndex: 'proxyUserCode',
            key: 'proxyUserCode',
            editable: true,
            render(text, record) {
                if (record.proxyEnable === 0) {
                    return record.proxyUserName;
                }
                return null;
            }
        },
        {
            title: '操作',
            dataIndex: 'operation',
            render: (text, record) => {
                const editable = isEditing(record);
                return editable ? (
                    <span>
                        <EditableContext.Consumer>
                            {newForm => (
                                <a onClick={() => save(newForm, record)} style={{ marginRight: 8 }}>
                                    保存
                                </a>
                            )}
                        </EditableContext.Consumer>
                        <a
                            onClick={e => {
                                e.preventDefault();
                                cancel(record.processKey);
                            }}
                        >
                            取消
                        </a>
                    </span>
                ) : (
                    <a disabled={editingKey !== ''} onClick={() => edit(record.processKey)}>
                        编辑
                    </a>
                );
            }
        }
    ].map(col => {
        if (!col.editable) {
            return col;
        }
        return {
            ...col,
            onCell: record => ({
                record,
                inputType: col.dataIndex,
                dataIndex: col.dataIndex,
                title: col.title,
                editing: isEditing(record)
            })
        };
    });
    return (
        <Modal
            footer={null}
            className={styles.modal}
            title="流程代理设置"
            visible={visible}
            onOk={onOk}
            maskClosable={false}
            {...rest}
        >
            <ConfigProvider getPopupContainer={trigger => trigger.parentNode}>
                <EditableContext.Provider value={form}>
                    <SimpleDataTable
                        fetchData={getData}
                        form={form}
                        formConfig={{}}
                        columns={columns}
                        dataSource={dataSource}
                        rowKey="id"
                        tableProps={{
                            components,
                            style: {
                                marginTop: 0
                            }
                        }}
                    >
                        {({ table }) => table}
                    </SimpleDataTable>
                </EditableContext.Provider>
            </ConfigProvider>
        </Modal>
    );
};

export default Form.create()(NewProxyModal);
